package gl.android.biyiqing.fragment;

import gl.App;
import gl.adapter.JsonArrayViewPagerAdapter;
import gl.adapter.SimpleAdapter;
import gl.android.biyiqing.FragmentContainerActivity;
import gl.android.biyiqing.MessageBoxActivity;
import gl.android.biyiqing.PartyInfoActivity;
import gl.android.biyiqing.PassWordResetActivity;
import gl.android.biyiqing.R;
import gl.android.biyiqing.SettingActivity;
import gl.android.biyiqing.api.API;
import gl.android.biyiqing.bean.BYQUserInfo;
import gl.android.biyiqing.competent.UnreadMessageTextview;
import gl.android.widget.viewpager.Banner;
import gl.common.AjaxCallBackProxy;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.uitls.AndroidUtil;

import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.cocosw.bottomsheet.BottomSheet;
import com.jfeinstein.jazzyviewpager.JazzyViewPager;
import com.viewpagerindicator.PageIndicator;

public class HomeFragment extends BaseFragment implements OnClickListener {

	private static final String TYPE_HOME = "1";
	private static int SEX = 2;
	private static int SEX_RECOMMND = 1;

	// Content View Elements

	private android.support.v4.view.ViewPager pager;
	private TextView textView1;
	private GridView gridView1;
	private TextView textView2;
	private GridView gridView2;
	private TextView textView3;
	private GridView gridView3;
	private TextView ll_menu_right2_tv;
	private View ll_menu_right2;
	private View ll_menu_right1;

	// End Of Content View Elements

	private void bindViews() {

		pager = (android.support.v4.view.ViewPager) rootView
				.findViewById(R.id.jazzy_pager);
		textView1 = (TextView) rootView.findViewById(R.id.more1);
		gridView1 = (GridView) rootView.findViewById(R.id.gridView1);
		textView2 = (TextView) rootView.findViewById(R.id.more2);
		gridView2 = (GridView) rootView.findViewById(R.id.gridView2);
		textView3 = (TextView) rootView.findViewById(R.id.more3);
		textView1.setOnClickListener(this);
		textView2.setOnClickListener(this);
		textView3.setOnClickListener(this);
		ll_menu_right2_tv = (TextView) rootView
				.findViewById(R.id.ll_menu_right2_tv);
		ll_menu_right2 = (View) rootView.findViewById(R.id.ll_menu_right1_iv);
		ll_menu_right2.setOnClickListener(this);
		ll_menu_right1 = (View) rootView.findViewById(R.id.ll_menu_right2_iv);
		ll_menu_right1.setOnClickListener(this);
		gridView3 = (GridView) rootView.findViewById(R.id.gridView3);
	}

	public static HomeFragment newInstance() {
		HomeFragment fragment = new HomeFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (banner != null) {
			banner.startLoop();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (banner != null) {
			banner.stopLoop();
		}
	}

	private int maxID;
	private UnreadMessageTextview mUnreadMessageTextview;
	private Banner banner;

	public HomeFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_home, container, false);
		bindViews();
		initData();
		SEX = UserManger.getInstance().userinfo.getGender();
		SEX_RECOMMND = (SEX == 1 ? 2 : 1);
		mUnreadMessageTextview = new UnreadMessageTextview(ll_menu_right2_tv);
		return rootView;
	}

	@Override
	public void onStart() {
		super.onStart();
		mUnreadMessageTextview.start();
	}

	@Override
	public void onStop() {
		super.onStop();
		mUnreadMessageTextview.stop();
	}
	protected boolean getRefreAble() {
		return true;
	}
	@Override
	public void onBGARefreshLayoutBeginRefreshing() {
		super.onBGARefreshLayoutBeginRefreshing();
		// 谁看过我
		final String[] from = new String[] { "username", "avatar",
				BYQUserInfo.KEY_SHENFEN,BYQUserInfo.KEY_GROUP,BYQUserInfo.KEY_VIP_UNIT };
		final int[] to = new int[] { R.id.tv_nick, R.id.iv_avator, R.id.age,
				R.id.iv_online,R.id.iv_vip };
		initUserList(from, to);
	}
	private void initData() {
		// 谁看过我
		final String[] from = new String[] { "username", "avatar",
				BYQUserInfo.KEY_SHENFEN,BYQUserInfo.KEY_GROUP,BYQUserInfo.KEY_VIP_UNIT };
		final int[] to = new int[] { R.id.tv_nick, R.id.iv_avator, R.id.age,
				R.id.iv_online,R.id.iv_vip };
		initGridView(gridView1, API.URL
				+ "GetHomeViewer?userid=%s&type=%s&maxid=%d", new Object[] {
				UserManger.getInstance().userid, TYPE_HOME, maxID },
				R.layout.item_grid_image, from, to);
		initUserList(from, to);

	}

	public void initUserList(final String[] from, final int[] to) {
		// 推荐会员
		initGridView(gridView2, API.URL
				+ "GetRecommends?userid=%s&sex=%s&type=%s&maxid=%d", new Object[] {
				UserManger.getInstance().userid,SEX_RECOMMND, TYPE_HOME, maxID }, R.layout.item_grid_image,
				from, to);
		// 单位会员
		initGridView(gridView3, API.URL + "GetCareer?userid="+UserManger.getInstance().userid+"&sex=%s&type=%s&maxid=%d",
				new Object[] { SEX, TYPE_HOME, maxID },
				R.layout.item_grid_image, from, to);
		// 活动
		initPagerView(pager, API.URL + "GetValidParty", new Object[] {},
				R.layout.item_bigimage, new String[] { "uploadfiles" },
				new int[] { R.id.iv_avator, R.id.iv_avator });
	}

	private void initPagerView(final ViewPager pager2, String url,
			Object[] pars, final int itemLayout, final String[] from,
			final int[] to) {

		BaseControl.get(url, new AjaxCallBackProxy() {
			@Override
			public void onSuccess(final String t) {
				if (!isValueFragment()) {
					return;
				}
				super.onSuccess(t);
				try {
					if (new JSONObject(t).getJSONArray("data") == null) {
						return;
					}

					pager2.setAdapter(new JsonArrayViewPagerAdapter(
							getActivity(), new JSONObject(t).get("data")
									.toString(), itemLayout, from, to,
							new SimpleAdapter.OnItemChildViewClick() {

								@Override
								public void onClick(View view, int position) {
									String partyid;
									try {
										partyid = new JSONObject(t)
												.getJSONArray("data")
												.getJSONObject(position)
												.getString(
														PartyInfoFragment.KEY_PARTYID);
										Intent intent = new Intent(view
												.getContext(),
												PartyInfoActivity.class);
										intent.putExtra(
												PartyInfoFragment.KEY_PARTYID,
												partyid);
										startActivity(intent);
									} catch (Exception e) {
										e.printStackTrace();
									}

								}
							}));

					banner = new Banner((JazzyViewPager) pager,
							((PageIndicator) findViewById(R.id.indicator)),
							(TextView) findViewById(R.id.pagerdescribe));
					banner.startLoop();
				} catch (Exception e) {
					e.printStackTrace();
					onFailure(e, 0, e.getMessage());
				}
			}
		}, pars);

	}

	private void initGridView(final GridView adpateview, String url,
			Object[] pars, final int itemLayout, final String[] from,
			final int[] to) {
		initAbsListView(adpateview, url, pars, itemLayout, from, to);
	}

	@Override
	protected String preFormatJsonData(String t) {
		System.out.println("preFormatJsonData:shenfen");
		return BYQUserInfo.preFormatShenFen(t);
	}

	private void showDialog() {
		new BottomSheet.Builder(getActivity()).title("设置").sheet(R.menu.menu_setting)
				.listener(new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case R.id.reset:
							startActivity(new Intent(getActivity(),PassWordResetActivity.class));
							break;
						case R.id.loginout:
							AndroidUtil.saveToSharePreferences("isAutoLogin", "0", "false");
							App.getApp().exit();
							break;
						}
					}
				}).show();
	}
	@Override
	public void onClick(View v) {
		if (v == ll_menu_right1) {
			mUnreadMessageTextview.setHasRead();
			Intent intent = new Intent(v.getContext(), MessageBoxActivity.class);
			getActivity().startActivity(intent);
		}
		else if (v == ll_menu_right2) {
			Intent intent = new Intent(v.getContext(), SettingActivity.class);
			getActivity().startActivity(intent);
//			showDialog();
		}
		else if (v == textView1) {
			final int value = 0;
			toMoreUserInfoActivity(value);
		}
		else if (v == textView2) {
			final int value = 1;
			toMoreUserInfoActivity(value);
		}
		else if (v == textView3) {
			final int value = 2;
			toMoreUserInfoActivity(value);
		}

	}

	public void toMoreUserInfoActivity(final int value) {
		Intent intent = new Intent(getActivity(),
				FragmentContainerActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(BaseFragment.KEY_USER_ID, String.valueOf(value));
		bundle.putString(FragmentContainerActivity.BaseFragmentClassName,
				UserListFragment.class.getName());
		intent.putExtras(bundle);
		getActivity().startActivity(intent);
	}

}
